#!/usr/bin/env node

const fs = require('fs');
const puppeteer = require('puppeteer');

const args = [
    '--autoplay-policy=user-gesture-required',
    '--disable-background-networking',
    '--disable-background-timer-throttling',
    '--disable-backgrounding-occluded-windows',
    '--disable-breakpad',
    '--disable-client-side-phishing-detection',
    '--disable-component-update',
    '--disable-default-apps',
    '--disable-dev-shm-usage',
    '--disable-domain-reliability',
    '--disable-extensions',
    '--disable-features=AudioServiceOutOfProcess',
    '--disable-hang-monitor',
    '--disable-ipc-flooding-protection',
    '--disable-notifications',
    '--disable-offer-store-unmasked-wallet-cards',
    '--disable-popup-blocking',
    '--disable-print-preview',
    '--disable-prompt-on-repost',
    '--disable-renderer-backgrounding',
    '--disable-speech-api',
    '--disable-sync',
    '--disable-gpu',
    '--disable-accelerated-2d-canvas',
    '--hide-scrollbars',
    '--ignore-gpu-blacklist',
    '--metrics-recording-only',
    '--mute-audio',
    '--no-default-browser-check',
    '--no-first-run',
    '--no-pings',
    '--no-zygote',
    '--password-store=basic',
    '--use-gl=swiftshader',
    '--use-mock-keychain',
    '--disable-setuid-sandbox',
    '--no-sandbox',
    '--disable-blink-features=AutomationControlled',
    '--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36'
];

const getLatestVersion = async () => {
    const browser = await puppeteer.launch({
        args: args
    });
    const page = await browser.newPage();
    await page.goto('https://web.whatsapp.com', {
        waitUntil: 'load',
        timeout: 0,
        referer: 'https://whatsapp.com/',
    });

    await page.waitForFunction(() => window.require && window.require('WAWebBuildConstants'));

    const version = await page.evaluate(() => {
        return window.require('WAWebBuildConstants').VERSION_STR;
    });

    await browser.close();
    return version;
};

const getCurrentVersion = () => {
    try {
        const versionFile = fs.readFileSync('./.version');
        return versionFile ? versionFile.toString().trim() : null;
    } catch(_) {
        return null;
    }
};

const updateInFile = (filePath, oldVersion, newVersion) => {
    const originalFile = fs.readFileSync(filePath);  
    const newFile = originalFile.toString().replaceAll(oldVersion, newVersion);

    fs.writeFileSync(filePath, newFile);
};

const updateVersion = async (oldVersion, newVersion) => {
    const filesToUpdate = [
        '../../src/util/Constants.js',
        '../../README.md',
    ];

    for (const file of filesToUpdate) {
        updateInFile(file, oldVersion, newVersion);
    }

    fs.writeFileSync('./.version', newVersion);  
};

(async () => {
    const currentVersion = getCurrentVersion();
    const version = (await getLatestVersion()) ?? currentVersion;

    console.log(`Current version: ${currentVersion}`);
    console.log(`Latest version: ${version}`);

    if (currentVersion !== version) {
        console.log('Updating files...');
        await updateVersion(currentVersion, version);
        console.log('Updated!');
    } else {
        console.log('No changes.');
    }
})();
